//
//  RegisterViewController.m
//  MidProject
//
//  Created by student9 on 2020/12/2.
//  Copyright © 2020 itlab. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController () {
    NSString *name;
    NSString *email;
    NSString *password;
    NSString *passwordCharity;
    NSString *warning;
}
@property (nonatomic, strong) UILabel *warningLabel;
@property (nonatomic, strong) UIButton *register_btn;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"注册";
    self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.jpg"]];
    
    __weak typeof(self) weakSelf = self;
    // 主图标
    UIImage *mainicon = [[UIImage imageNamed:@"mainicon.png"] TransformtoSize:CGSizeMake(100, 100)];
    UIImageView *mainIconView = [[UIImageView alloc] initWithImage:mainicon];
    [self.view addSubview:mainIconView];
    [mainIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(weakSelf.view.frame.size.height/6);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(mainicon.size.width, mainicon.size.height));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 账号框
    // 输入框主体
    JVFloatLabeledTextField *usernameTF = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100, 50)];
    // 边框线宽度
    usernameTF.layer.borderWidth = 1;
    // 边框线颜色
    usernameTF.layer.borderColor = [UIColor grayColor].CGColor;
    // 输入文字颜色
    usernameTF.textColor = [UIColor blackColor];
    // 浮动式标签的正常字体颜色
    usernameTF.floatingLabelTextColor = [UIColor grayColor];
    // 输入框成为第一响应者时,浮动标签的文字颜色.
    usernameTF.floatingLabelActiveTextColor = [UIColor blueColor];
    // 指明当输入文字时,是否下调基准线(baseline).设置为YES(非默认值),意味着占位内容会和输入内容对齐.
    usernameTF.keepBaseline = YES;
    // 允许编辑
    [usernameTF setEnabled:YES];
    // 设置初始占位符
    [usernameTF setPlaceholder:@"Input your Username"
                 floatingTitle:@"Username"];
    usernameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    //关闭系统自动联想
    usernameTF.autocorrectionType=UITextAutocorrectionTypeNo;
    //关闭首字母大写
    usernameTF.autocapitalizationType=UITextAutocapitalizationTypeNone;
    // 设置边框类型
    [usernameTF setKeyboardType:UIKeyboardTypeDefault];
    // 设置一个左边的空白空间，防止文字直接贴边，并设置为总是显示UITextFieldViewModeAlways
    [usernameTF setLeftView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 0)]];
    [usernameTF setLeftViewMode:UITextFieldViewModeAlways];
    // 设置背景颜色，为了美观设置了透明度
    UIColor *color = [UIColor whiteColor];
    usernameTF.backgroundColor = [color colorWithAlphaComponent:0.8];
    UIBezierPath * maskPathUsername = [UIBezierPath bezierPathWithRoundedRect:usernameTF.bounds cornerRadius:10];
    CAShapeLayer * maskLayerUsername = [[CAShapeLayer alloc] init];
    maskLayerUsername.frame = usernameTF.bounds;
    maskLayerUsername.path = maskPathUsername.CGPath;
    usernameTF.layer.mask = maskLayerUsername;
    // 监听事件UIControlEventEditingChanged，当输入的内容改变之后，便调用textFieldDidChangeDate
    [usernameTF addTarget:self
                   action:@selector(textFieldDidChangeUsername:)
         forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:usernameTF];
    [usernameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 2);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 邮箱框
    // 输入框主体
    JVFloatLabeledTextField *emailTF = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100, 50)];
    // 边框线宽度
    emailTF.layer.borderWidth = 1;
    // 边框线颜色
    emailTF.layer.borderColor = [UIColor grayColor].CGColor;
    // 输入文字颜色
    emailTF.textColor = [UIColor blackColor];
    // 浮动式标签的正常字体颜色
    emailTF.floatingLabelTextColor = [UIColor grayColor];
    // 输入框成为第一响应者时,浮动标签的文字颜色.
    emailTF.floatingLabelActiveTextColor = [UIColor blueColor];
    // 指明当输入文字时,是否下调基准线(baseline).设置为YES(非默认值),意味着占位内容会和输入内容对齐.
    emailTF.keepBaseline = YES;
    // 允许编辑
    [emailTF setEnabled:YES];
    // 设置初始占位符
    [emailTF setPlaceholder:@"Input your Email"
              floatingTitle:@"Email"];
    emailTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    //关闭系统自动联想
    emailTF.autocorrectionType=UITextAutocorrectionTypeNo;
    //关闭首字母大写
    emailTF.autocapitalizationType=UITextAutocapitalizationTypeNone;
    // 设置边框类型
    [emailTF setKeyboardType:UIKeyboardTypeDefault];
    // 设置一个左边的空白空间，防止文字直接贴边，并设置为总是显示UITextFieldViewModeAlways
    [emailTF setLeftView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 0)]];
    [emailTF setLeftViewMode:UITextFieldViewModeAlways];
    // 设置背景颜色，为了美观设置了透明度
    UIColor *colorEmail = [UIColor whiteColor];
    emailTF.backgroundColor = [colorEmail colorWithAlphaComponent:0.8];
    UIBezierPath * maskPathEmail = [UIBezierPath bezierPathWithRoundedRect:emailTF.bounds cornerRadius:10];
    CAShapeLayer * maskLayerEmail = [[CAShapeLayer alloc] init];
    maskLayerEmail.frame = emailTF.bounds;
    maskLayerEmail.path = maskPathEmail.CGPath;
    emailTF.layer.mask = maskLayerEmail;
    // 监听事件UIControlEventEditingChanged，当输入的内容改变之后，便调用textFieldDidChangeDate
    [emailTF addTarget:self
                action:@selector(textFieldDidChangeEmail:)
      forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:emailTF];
    [emailTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 2 + 60);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 密码框
    // 输入框主体
    JVFloatLabeledTextField *passwordTF = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100, 50)];
    // 边框线宽度
    passwordTF.layer.borderWidth = 1;
    // 边框线颜色
    passwordTF.layer.borderColor = [UIColor grayColor].CGColor;
    // 输入文字颜色
    passwordTF.textColor = [UIColor blackColor];
    // 浮动式标签的正常字体颜色
    passwordTF.floatingLabelTextColor = [UIColor grayColor];
    // 输入框成为第一响应者时,浮动标签的文字颜色.
    passwordTF.floatingLabelActiveTextColor = [UIColor blueColor];
    // 指明当输入文字时,是否下调基准线(baseline).设置为YES(非默认值),意味着占位内容会和输入内容对齐.
    passwordTF.keepBaseline = YES;
    // 密码隐藏
    passwordTF.secureTextEntry = YES;
    // 允许编辑
    [passwordTF setEnabled:YES];
    // 设置初始占位符
    [passwordTF setPlaceholder:@"Input your Password"
                 floatingTitle:@"Password"];
    passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    //关闭系统自动联想
    passwordTF.autocorrectionType=UITextAutocorrectionTypeNo;
    //关闭首字母大写
    passwordTF.autocapitalizationType=UITextAutocapitalizationTypeNone;
    // 设置边框类型
    [passwordTF setKeyboardType:UIKeyboardTypeDefault];
    // 设置一个左边的空白空间，防止文字直接贴边，并设置为总是显示UITextFieldViewModeAlways
    [passwordTF setLeftView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 0)]];
    [passwordTF setLeftViewMode:UITextFieldViewModeAlways];
    // 设置背景颜色，为了美观设置了透明度
    UIColor *colorPassword = [UIColor whiteColor];
    passwordTF.backgroundColor = [colorPassword colorWithAlphaComponent:0.8];
    UIBezierPath * maskPathPassword = [UIBezierPath bezierPathWithRoundedRect:passwordTF.bounds cornerRadius:10];
    CAShapeLayer * maskLayerPassword = [[CAShapeLayer alloc] init];
    maskLayerPassword.frame = passwordTF.bounds;
    maskLayerPassword.path = maskPathPassword.CGPath;
    passwordTF.layer.mask = maskLayerPassword;
    // 监听事件UIControlEventEditingChanged，当输入的内容改变之后，便调用textFieldDidChangeDate
    [passwordTF addTarget:self
                   action:@selector(textFieldDidChangePassword:)
         forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:passwordTF];
    [passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 2 + 120);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 密码确认框
    // 输入框主体
    JVFloatLabeledTextField *charifypasswordTF = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100, 50)];
    // 边框线宽度
    charifypasswordTF.layer.borderWidth = 1;
    // 边框线颜色
    charifypasswordTF.layer.borderColor = [UIColor grayColor].CGColor;
    // 输入文字颜色
    charifypasswordTF.textColor = [UIColor blackColor];
    // 浮动式标签的正常字体颜色
    charifypasswordTF.floatingLabelTextColor = [UIColor grayColor];
    // 输入框成为第一响应者时,浮动标签的文字颜色.
    charifypasswordTF.floatingLabelActiveTextColor = [UIColor blueColor];
    // 指明当输入文字时,是否下调基准线(baseline).设置为YES(非默认值),意味着占位内容会和输入内容对齐.
    charifypasswordTF.keepBaseline = YES;
    // 密码隐藏
    charifypasswordTF.secureTextEntry = YES;
    // 允许编辑
    [charifypasswordTF setEnabled:YES];
    // 设置初始占位符
    [charifypasswordTF setPlaceholder:@"Input your Password AGAIN"
                 floatingTitle:@"Password"];
    charifypasswordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    //关闭系统自动联想
    charifypasswordTF.autocorrectionType=UITextAutocorrectionTypeNo;
    //关闭首字母大写
    charifypasswordTF.autocapitalizationType=UITextAutocapitalizationTypeNone;
    // 设置边框类型
    [charifypasswordTF setKeyboardType:UIKeyboardTypeDefault];
    // 设置一个左边的空白空间，防止文字直接贴边，并设置为总是显示UITextFieldViewModeAlways
    [charifypasswordTF setLeftView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 0)]];
    [charifypasswordTF setLeftViewMode:UITextFieldViewModeAlways];
    // 设置背景颜色，为了美观设置了透明度
    UIColor *colorPasswordCharity = [UIColor whiteColor];
    charifypasswordTF.backgroundColor = [colorPasswordCharity colorWithAlphaComponent:0.8];
    UIBezierPath * maskPathPasswordCharity = [UIBezierPath bezierPathWithRoundedRect:charifypasswordTF.bounds cornerRadius:10];
    CAShapeLayer * maskLayerPasswordCharity = [[CAShapeLayer alloc] init];
    maskLayerPasswordCharity.frame = charifypasswordTF.bounds;
    maskLayerPasswordCharity.path = maskPathPasswordCharity.CGPath;
    charifypasswordTF.layer.mask = maskLayerPasswordCharity;
    // 监听事件UIControlEventEditingChanged，当输入的内容改变之后，便调用textFieldDidChangeDate
    [charifypasswordTF addTarget:self
                   action:@selector(textFieldDidChangePasswordCharity:)
         forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:charifypasswordTF];
    [charifypasswordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 2 + 180);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    _warningLabel = [[UILabel alloc] init];
    _warningLabel.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 20);
    _warningLabel.textColor = [UIColor redColor];
    [self.view addSubview:_warningLabel];
    [_warningLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 2 + 240);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 20));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 注册按钮
    _register_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _register_btn.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 50);
    _register_btn.backgroundColor = [UIColor colorWithRed:250/255.0 green:128/255.0 blue:114/255.0 alpha:1.0];
    [_register_btn setTitle:@"Register" forState:UIControlStateNormal];
    [_register_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBezierPath * maskPath_register = [UIBezierPath bezierPathWithRoundedRect:_register_btn.bounds cornerRadius:10];
    CAShapeLayer * maskLayer_register = [[CAShapeLayer alloc] init];
    maskLayer_register.frame = _register_btn.bounds;
    maskLayer_register.path = maskPath_register.CGPath;
    _register_btn.layer.mask = maskLayer_register;
    [_register_btn addTarget:self
                     action:@selector(RegisterViewPush:)
           forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_register_btn];
    [_register_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 2 + 270);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    [_register_btn setUserInteractionEnabled:NO];
}

- (void)RegisterViewPush: (UIButton *)buttonView {
    NSDictionary *usernameAndPassword = [[NSDictionary alloc] initWithObjectsAndKeys: self->name, @"name", self->email, @"email", self->password , @"password" ,nil ];
    NSString *urlString = @"http://172.18.178.56/api/user/register";
    NSURL *url = [NSURL URLWithString:urlString];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:usernameAndPassword options:NSJSONWritingPrettyPrinted error:&error];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:jsonData];
    NSURLSession *session = [NSURLSession sharedSession];
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *return_data, NSURLResponse *response, NSError *error) {       
        NSError *jsonError;
        NSDictionary *jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:return_data options:kNilOptions error:&jsonError];
        if(jsonError) {
            // check the error description
            NSLog(@"json error : %@", [jsonError localizedDescription]);
        } else {
            // use the jsonDictionaryOrArray
            if ([jsonDictionaryOrArray[@"State"]  isEqual: @"success"]) {
                NSLog(@"json : success");
                self.register_state = true;
            } else {
                NSLog(@"json : error");
                self.register_state = false;
            }
        }
        dispatch_semaphore_signal(semaphore);
    }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
    if (self.register_state == true) {
        [self.navigationController popViewControllerAnimated: YES];
        
    } else {
        NSLog(@"you cant. why?");
        [self.navigationController popViewControllerAnimated: YES];
    }
    
}

- (void) textFieldDidChangeUsername:(UITextField*) sender {
    self->name = sender.text;
    if ([self->name isEqualToString:@""] == YES) {
        _warningLabel.text = @"name不能为空";
    } else {
        _warningLabel.text = @"";
        if([self->password isEqualToString:@""] == NO && [self->email isEqualToString:@""] == NO && [self->passwordCharity isEqualToString:self->password] == YES) {
            [_register_btn setUserInteractionEnabled: YES];
        }
    }
}

- (void) textFieldDidChangePassword:(UITextField*) sender {
    self->password = sender.text;
    if ([self->password isEqualToString:@""] == YES) {
        _warningLabel.text = @"password不能为空";
    } else {
        _warningLabel.text = @"";
        if([self->name isEqualToString:@""] == NO && [self->email isEqualToString:@""] == NO && [self->passwordCharity isEqualToString:self->password] == YES) {
            [_register_btn setUserInteractionEnabled: YES];
        }
    }
}

- (void) textFieldDidChangeEmail:(UITextField*) sender {
    self->email = sender.text;
    if ([self->email isEqualToString:@""] == YES) {
        _warningLabel.text = @"email不能为空";
    } else {
        _warningLabel.text = @"";
        if([self->name isEqualToString:@""] == NO && [self->password isEqualToString:@""] == NO && [self->passwordCharity isEqualToString:self->password] == YES) {
            [_register_btn setUserInteractionEnabled: YES];
        }
    }
}

- (void) textFieldDidChangePasswordCharity:(UITextField*) sender {
    self->passwordCharity = sender.text;
    if ([self->passwordCharity isEqualToString:self->password] == NO) {
        _warningLabel.text = @"两次输入密码不一致";
    } else {
        _warningLabel.text = @"";
        if([self->name isEqualToString:@""] == NO && [self->password isEqualToString:@""] == NO && [self->email isEqualToString:@""] == NO) {
            [_register_btn setUserInteractionEnabled: YES];
        }
    }
}

-(void)leftDrawerButtonPress:(id)sender {
    [self.drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
